import { observer } from "mobx-react";
import "./style/slide.less"
import { WeaRangePicker, WeaHelpfulTip, WeaNewScroll, WeaInput, WeaUpload, WeaProgress, WeaBrowser, WeaReqTop } from 'ecCom';
import { Row, Col, Tooltip, Menu, InputNumber, Modal, Tabs, message } from 'antd';
import { WeaSwitch } from 'comsMobx'
import PrjDateTime from '../comp/prj-data-time'
import { datediff } from '../../util/index'
const basicToolBar = {
    uploadUrl: "/api/blog/fileupload/uploadimage", 
    startupFocus: false,
    toolbar: [
        { name: 'markdown', items: ['Markdown'] },
        { name: 'document', items: ['Source', '-', 'Save', 'NewPage', 'Preview', '-', 'Templates'] },
        { name: 'clipboard', items: ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo'] },
        { name: 'basicstyles', items: ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'CopyFormatting', 'RemoveFormat'] },
        { name: 'styles', items: ['Styles', 'Format', 'Font', 'FontSize'] },
        { name: 'colors', items: ['TextColor', 'BGColor'] },
        { name: 'tools', items: ['Maximize', 'ShowBlocks'] },
        { name: 'insert', items: ['Image', 'Table', 'Smiley'] }
    ],
};
import RelareExchange from '../common/relateExchange'
import RelateWorkFlow from '../common/relateWorkFlow'
import RelateDocument from "../common/relateDocument"

@observer
export default class TaskForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            contentHight: 650,
            taskInfo: {
                subject: "",
                hrmid: "",
                hrmname: "",
                begindate: "",
                enddate: ""
            },
            seletedKey : "0"
        }
    }

    componentDidMount() {
        this.setState({
            contentHight: window.innerHeight - 220
        });
    }

    getSearchs() {
        const conditioninfo = this.props.contentStore.datas;
        const { cardform, setTaskCardFields, taskInfo } = this.props.contentStore;
        const { isFormInit } = cardform;
        let group = [];
        const formParams = cardform.getFormParams();
        isFormInit && conditioninfo.map(c => {
            let items = [];
            let index = 1;
            c.items.map(field => {
                let col = 4;
                //if (field.conditionType.toUpperCase() == WeaTools.types.CASCADER) col = 1;
                let hasIcons = typeof (field.icons) !== "undefined";
                if (hasIcons) {
                    col = 2;
                }
                let dom;

                //    if (field.viewAttr == "1" || (field.conditionType == "BROWSER" && field.browserConditionParam.viewAttr == "1")) { field.hasBorder = true }  //只读样式控制
                if (field.domkey[0] == "begindate") {
                    dom =
                        <PrjDateTime
                            {...field}
                            endValue={formParams.enddate ? new Date(formParams.enddate) : null}
                            value={[formParams.begindate, formParams.begintime]}
                            onChange={(v) => { setTaskCardFields({ begindate__begintime: { value: v } }); this.workdayComputed(v, "begin") }} />

                } else if (field.domkey[0] == "enddate") {
                    dom =
                        <PrjDateTime
                            {...field}
                            value={[formParams.enddate, formParams.endtime]}
                            startValue={formParams.begindate ? new Date(formParams.begindate) : null}
                            onChange={(v) => {
                                if (taskInfo.maxSubTaskEndDate == "" || typeof (taskInfo.maxSubTaskEndDate) == "undefined") {
                                    setTaskCardFields({ enddate__endtime: { value: v } });
                                    this.workdayComputed(v, "end")
                                } else {
                                    if (new Date(v[0]) < new Date(taskInfo.maxSubTaskEndDate)) {
                                        // Modal.warning({
                                        //     title: getLabel(83887, "任务完成的最后时间小于其子任务完成的最后时间！"),
                                        //     content: ""
                                        // });
                                        message.error(getLabel(83887, "任务完成的最后时间小于其子任务完成的最后时间！"));
                                        setTaskCardFields({ enddate__endtime: { value: [taskInfo.maxSubTaskEndDate, formParams.endtime] } });
                                        this.workdayComputed([taskInfo.maxSubTaskEndDate, formParams.endtime], "end")
                                    } else {
                                        setTaskCardFields({ enddate__endtime: { value: v } });
                                        this.workdayComputed(v, "end")
                                    }
                                }
                            }} />

                } else if (field.domkey[0] == "actualbegindate") {
                    dom =
                        <PrjDateTime
                            endValue={formParams.actualenddate ? new Date(formParams.actualenddate) : null}
                            {...field}
                            value={[formParams.actualbegindate, formParams.actualbegintime]}
                            onChange={(v) => { setTaskCardFields({ actualbegindate__actualbegintime: { value: v } }); this.onActualComputed(v, "begin") }} />

                } else if (field.domkey[0] == "actualenddate") {
                    dom =
                        <PrjDateTime startValue={formParams.actualbegindate ? new Date(formParams.actualbegindate) : null} {...field}
                            value={[formParams.actualenddate, formParams.actualendtime]}
                            onChange={(v) => { setTaskCardFields({ actualenddate__actualendtime: { value: v } }); this.onActualComputed(v, "end") }} />

                } else if (field.domkey[0] == "finish") {
                    if (field.viewAttr == "1") {
                        dom =
                            <WeaProgress percent={field.value || 0} strokeColor={field.strokeColor} status="active" />

                    } else {
                        dom =
                            <span><InputNumber min={0} value={formParams.finish}
                                onChange={(v) => { this.checkProgress(v); }} />
                                <span style={{ marginLeft: 5 }}>%</span></span>

                    }
                } else if (field.conditionType == "RICHTEXT") {   //多行文本
                    let domkey = field.domkey[0];
                    if (field.viewAttr == "1") {
                        dom =
                            <div dangerouslySetInnerHTML={{ __html: field.value }}></div>

                    } else {
                        //     dom = <Row>
                        //     <Col span={24} style={{'margin-right':'5px'}}>
                        //         <WeaRichText
                        //             value = {formParams[domkey]}
                        //             ckConfig={basicToolBar}
                        //             onChange={v => {setTaskCardFields({[domkey]:{value:v}})}}
                        //             bottomBarConfig={[]}
                        //         />
                        //     </Col>
                        //   </Row>
                        dom = <WeaSwitch fieldConfig={{ ...field, ckConfig: basicToolBar }} form={cardform} />
                    }
                } else if (field.domkey[0] == "accessory") {
                    let domkey = field.domkey[0];
                    dom =
                        <WeaUpload
                            uploadId={[domkey]}
                            uploadUrl={"/api/proj/prjutil/fileUpload?accsec=" + field.accsec}
                            category={field.accsec}
                            autoUpload={true}
                            showBatchLoad={false}
                            showClearAll={false}
                            multiSelection={true}
                            datas={field.datas}
                            maxUploadSize={field.accsize}
                            onChange={v => { setTaskCardFields({ [domkey]: { value: v } }) }}
                            viewAttr={field.viewAttr}
                        // onUploading={(state)=>{}}
                        />

                } else {
                    dom = <WeaSwitch fieldConfig={field} form={cardform} onChange={this.onChangeDatas.bind(this)} onBlur={this.onBlurDatas.bind(this)} />;
                }
                items.push({
                    com: (<div class={index > 1 ? "taskContentLine taskContentBoxLine" : "taskContentLine"}>
                        <Row>
                            <Col span={col}>
                                {
                                    hasIcons &&
                                    <Tooltip placement="bottom" title={`${field.label}`}>
                                        <i className={"taskContentBoxIcon " + field.icons}></i>
                                    </Tooltip>
                                }
                                {
                                    !hasIcons &&
                                    <span class="fieldName" title={field.label}>{field.label}</span>
                                }
                            </Col>
                            <Col span={24 - col}>
                                {dom}
                            </Col>
                        </Row>
                    </div>),
                    hide: cardform.isHide(field, (keys, allParams) => {
                        return false;
                    })
                })
                index++;
            });
            group.push(
                <div className="taskContentBox">
                    <div className="taskContentBoxBlock  mTop10 pTop15">
                        {items && items.map((obj) => {
                            if (obj) {
                                return (
                                    obj.com
                                )
                            }
                        })
                        }
                    </div>
                </div>)
        });
        return group;
    }

    reloadTask = (id) => {
        this.props.contentStore.loadTaskInfo({ prjid: this.props.prjid, taskid: id });
    }

    getChildList() {
        const { taskInfo } = this.props.contentStore;
        let list = [];
        let dom;
        if (taskInfo.childList) {
            taskInfo.childList.map(item => {
                dom =
                    <li >
                        <div class="subTasksStatusWidth">
                            <Tooltip placement="bottom" title={"点击查看任务信息"}>
                                <span className="icon-coms-category" onClick={(e) => { this.reloadTask(item.id) }} />
                            </Tooltip>
                        </div>
                        <div class="subTasksNameMain" >
                            {item.subject}
                        </div>
                        <div class="subTasksOperator">
                            <Tooltip placement="bottom" title={item.hrmname}>
                                <a href={'javaScript:openhrm(' + item.hrmid + ');'} onClick={e => window.pointerXY(e)} >
                                    <img src={item.hrmicon} className="sub-task-manager-img" />
                                </a>
                            </Tooltip>
                        </div>
                    </li>
                list.push(dom);
            })
        }

        return list;

    }
    onChangeDatas(data) {
        const { cardform } = this.props.contentStore;
        cardform.validateForm().then(f => {
            if (f.isValid) {
                // 验证通过, balabala业务代码
            } else {
                f.showErrors();
                this.setState({ date: new Date() }); // 改变一个state的变量,强制页面刷新
            }
        });
    }
    onBlurDatas(data) {
    }

    render() {
        const { taskObj, taskLoading, datas, taskInfo, selectTabKey, changeTab } = this.props.contentStore;
        const {hasRight } = this.props.contentStore;
        let enddate = new Date(Date.parse(taskObj.enddate.replace(/-/g, "/")));
        let actualEndDate = new Date(Date.parse(taskObj.actualEndDate.replace(/-/g, "/")));
        let today = new Date();
        let notend = taskObj.finish < 100;//未完成
        let isException = enddate < today || actualEndDate > enddate;//是否超期 
        if (notend && isException) {
            progressText = "超期";
            progressStatus = "exception";
        } else if (notend) {
            progressText = "计划";
            progressStatus = "active";
        } else {
            progressText = "完成";
            progressStatus = "success";
        }

        const menu = (
            <Menu>
                <Menu.Item key="0">
                    <a href="#" >删除任务</a>
                </Menu.Item>
                <Menu.Item key="1">
                    <a href="http://www.taobao.com/">第二个菜单项</a>
                </Menu.Item>
                {/* <Menu.Divider /> */}
                <Menu.Item key="3">第三个菜单项</Menu.Item>
            </Menu>
        );

        let topTab = [
            {
              color: '#000000',
              groupid: 'baseInfo',
              showcount: false,
              title: '基本信息',
              viewcondition: 0,
              key : 0
            },
            {
              color: '#ff3232',
              groupid: 'exchange',
              showcount: true,
              title: '相关交流',
              viewcondition: 1,
              key : 1
            }
          ];

        return (
            //
            <div className="wea-prj-slide">
                {/* <div className="wea-prj-slide-top">
                    <Row>
                        <Col span={4}>
                            <div className="wea-new-top-title" style={{ paddingTop: "8px" }}>
                                <div className="icon-circle-base" style={{ background: '#5d635f' }}>
                                    <i className="icon-coms-project"></i>
                                </div>
                                <span className="wea-new-top-title-breadcrumb" title="项目" style={{ verticalAlign: "middle" }}>
                                    任务
                                </span>
                            </div>
                        </Col>
                        <Col span={20}>
                            <div className="wea-prj-slide-top-operation">
                                {hasRight && <Row>
                                    <Col span={15}>
                                    </Col>
                                    <Col span={4}>
                                        <span>
                                            <i className={"taskContentBoxIcon icon-coms-Update-synchronization"}></i>
                                            &nbsp;刷新
                                            </span>
                                    </Col>
                                    {/* <Col span={4}>
                                            <Tooltip placement="bottom" title={"点击新建子任务"}>
                                                <span>
                                                    <i className={"taskContentBoxIcon icon-coms-currency-Task"}></i>
                                                    &nbsp;子任务
                                                </span>
                                            </Tooltip>
                                        </Col>  
                                    <Col span={4}>
                                        <Tooltip placement="bottom" title={"点击保存任务信息"}>
                                            <span onClick={(e) => { this.saveTask(e) }}>
                                                <i className={"taskContentBoxIcon icon-coms-Save-as"}></i>
                                                &nbsp;保存
                                                </span>
                                        </Tooltip>
                                    </Col>
                                  
                                    <Col span={1}>
                                        <span>
                                            <Dropdown overlay={menu} trigger={['click']}>
                                                <Tooltip placement="bottomRight" title={"更多操作"}>
                                                    <i className={"taskContentBoxIcon icon-coms-more"}></i>
                                                </Tooltip>
                                            </Dropdown>
                                        </span>
                                    </Col>
                                </Row>}
                            </div>
                        </Col>
                    </Row>
                     
                </div> */}
                 <WeaReqTop
                    title={'任务'}
                    icon={<i className='icon-coms-project' />}
                    iconBgcolor={'#5d635f'}
                    // loading={loading}
                    // buttons={btns}
                    buttonSpace={10}
                    showDropIcon={true}
                    // dropMenuDatas={dropMenuDatas}
                    // onDropMenuClick={this.onDropMenuClick}
                    tabDatas={topTab}
                    selectedKey={selectTabKey}
                    onChange={(key)=>{
                        changeTab(key)
                    }}
                >
                    <div className="wea-prj-slide-content"  >
                    {  <WeaNewScroll height={"100%"} onScroll={(e) => { }} style={{backgroundColor:"white"}} >
                        {/* <Spin spinning={taskLoading} style={{ height: "100%" }}>  */}
                        <div  height={"100%"} style={{display: selectTabKey == "0" ? "":"none"}} >
                            {this.getSearchs()}
                            {!taskLoading && <div className="taskContentBox">
                                <div className="taskContentBoxBlock  mTop10 pTop15">
                                    <div class="taskContentLine">
                                        <Row>
                                            <Col span={2}>
                                                <i className={"taskContentBoxIcon icon-coms-task-list"}></i>
                                            </Col>
                                            <Col span={22}>
                                                <span className={"taskContentBoxTopTitle"}>子任务 {taskInfo.finishnum}/{taskInfo.allnum}</span>
                                                <WeaHelpfulTip style={{ marginLeft: '10px' }} width={196} className={"taskContentBoxIcon"} title="在这里写入相应的提示信息在这里写入相应的提示信息在这里写入相应的提示信息" />
                                            </Col>
                                        </Row>
                                        <Row>
                                            <Col span={2}>
                                            </Col>
                                            <Col span={22}>
                                                <ul className={"slideSubTask"}>
                                                    {
                                                        this.getChildList()
                                                    }
                                                    <li style={{ display: "none" }} id="addTaskLine">
                                                        <div class="subTasksStatusWidth" style={{marginTop:"12px"}}>
                                                            <Tooltip placement="bottom" title={"点击保存子任务"}>
                                                                <span className="icon-coms-Save-as" onClick={(e) => { this.saveSubTask() }} />
                                                            </Tooltip>
                                                        </div>
                                                        <div class="subTasksNameMain">
                                                            <WeaInput
                                                                placeholder={"任务名称"} 
                                                                onChange={(v)=>{ this.setNewTaskValue("subject",v) }}
                                                            />
                                                            {/* <Input placeholder={"任务名称"} onChange={(v)=>{ this.setNewTaskValue("subject",v) }} id="addSubTaskInput" /> */}
                                                        </div>
                                                        <div class="subTasksOperator">
                                                            <WeaBrowser
                                                                type={1}
                                                                customized
                                                                textDecoration={true}
                                                                inputStyle={{ width: 200 }}
                                                                onChange={(ids, names, datas) => this.setNewTaskValue("hrmid", { hrmid: ids, hrmname: names })}
                                                            >
                                                                <Tooltip placement="bottom" title={this.state.taskInfo.hrmname == "" ? "请选择任务负责人" : this.state.taskInfo.hrmname}>
                                                                    {/* <a href={'javaScript:openhrm(' + item.hrmid + ');'} onClick={e => window.pointerXY(e)} > */}
                                                                    <img src={"/messager/images/icon_w_wev8.jpg"} className="sub-task-manager-img" style={{ marginTop: "5px" }} />
                                                                    {/* </a> */}
                                                                </Tooltip>
                                                            </WeaBrowser>
                                                            <Tooltip placement="bottom" trigger={['hover']} title={this.state.taskInfo.begindate == "" ? "请选择任务开始结束时间" : (this.state.taskInfo.begindate + " : " + this.state.taskInfo.enddate)}>
                                                                <WeaRangePicker
                                                                    value={[this.state.taskInfo.begindate, this.state.taskInfo.enddate]}
                                                                    onChange={v => this.setNewTaskValue("startenddate", v)}
                                                                />
                                                            </Tooltip>
                                                        </div>
                                                    </li>
                                                </ul>
                                                {hasRight && <span className={"addTaskSubBtn pointer ThemeColor3"} id="addTaskBtn" onClick={(e) => { this.onTaskAdd(e) }}>
                                                    <i className={"icon-coms-Add-to"}></i>添加子任务
                                                </span>}
                                            </Col>
                                        </Row>

                                    </div>
                                </div>
                            </div>}
                            <div style={{paddingTop:"20px"}}>
                            </div>
                        </div>

                        <div height={"100%"} style={{display: selectTabKey == "1" ? "":"none"}}>
                            <RelareExchange contentStore={this.props.boardStore.prjTaskStore} callBack={()=>{this.reloadExchanges()}} key={new Date().getTime()}  />     
                        </div>           
                        <div height={"100%"} style={{display: selectTabKey == "2" ? "":"none",backgroundColor:"white"}}>
                               
                        </div>    
                    </WeaNewScroll>}
                </div>
                 </WeaReqTop>
            </div>
        )
    }
    commitDiscuss = () =>{
        const discuss =  jQuery("#discussArea").val();
        if(discuss!=""){
            this.props.saveDiscuss({
                discuss : discuss,
                taskid : this.props.contentStore.taskid
            });
            jQuery("#discussArea").val("");
        }
    }

    reloadExchanges=()=>{
        const {prjTaskStore} = this.props.boardStore;
        prjTaskStore.getRelateExchangeInfo();
    }

    getDiscuss = () => {
        const { taskInfo } = this.props.contentStore;

        let list = [];
        let dom;
        if (taskInfo.discuss) {
            taskInfo.discuss.map(item => {
                dom =
                    <div class="taskContentLine taskContentBoxLine">
                        <Row>
                            <Col span={2} style={{ marginTop: "5px" }}>
                                <Tooltip placement="bottom" title={item.hrmname}>
                                    <a href={'javaScript:openhrm(' + item.hrmid + ');'} onClick={e => window.pointerXY(e)} >
                                        <img src={item.hrmicons} className="discuss-manager-img" />
                                    </a>
                                </Tooltip>
                            </Col>
                            <Col span={1}>
                            </Col>
                            <Col span={16}>
                                {item.discuss}
                            </Col>
                            <Col span={1}>
                            </Col>
                            <Col span={4}>
                                {item.discussDate}
                            </Col>
                        </Row>
                    </div>
                list.push(dom);
            })
        }
        return list;

    }

    workdayComputed = (arg, type) => {
        const { setTaskCardFields, taskInfo: { passnoworktime, userid } } = this.props.contentStore;
        const { cardform } = this.props.contentStore;
        const formParams = cardform.getFormParams() || {};
        let res = "";
        if (type == "begin") {
            if (arg[0] && formParams.enddate) {
                res = datediff(arg[0], formParams.enddate, arg[1] || "00:00", formParams.endtime || "23:59", userid, passnoworktime);
            }
        } else {
            if (arg[0] && formParams.begindate) {
                res = datediff(formParams.begindate, arg[0], formParams.begintime || "00:00", arg[1] || "23:59", userid, passnoworktime);
            }
        }
        setTaskCardFields({ workday: { value: res } });
    }

    onActualComputed = (arg, type) => { //maxSubTaskEndDate
        const { setTaskCardFields, taskInfo: { passnoworktime, userid } } = this.props.contentStore;
        const { cardform } = this.props.contentStore;
        const formParams = cardform.getFormParams() || {};
        let res = "0";
        if (type == "begin") {
            if (arg[0] && formParams.actualenddate) {
                res = datediff(arg[0], formParams.actualenddate, arg[1] || "00:00", formParams.actualendtime || "23:59", userid, passnoworktime);
            }
        } else {
            if (arg[0] && formParams.actualbegindate) {
                res = datediff(formParams.actualbegindate, arg[0], formParams.actualbegintime || "00:00", arg[1] || "23:59", userid, passnoworktime);
            }
        }
        setTaskCardFields({ realmandays: { value: res } })
    }

    onTaskAdd = (e) => {
        $("#addTaskLine").css("display", "");
        $("#addTaskBtn").css("display", "none");
        $("#addTaskInput").focus();
    }

    checkProgress = (value) => {  //进度编辑校验
        const { taskInfo, setTaskCardFields } = this.props.contentStore;
        if (Number(taskInfo.finishmax) == 99) {
            if (value > 99) {
                // Modal.warning({
                //     title: getLabel(383829, "该任务所必须的相关文档或者相关流程不存在，任务不能完成100%。"),
                //     content: '',
                // });
                message.error(getLabel(383829, "该任务所必须的相关文档或者相关流程不存在，任务不能完成100%。"));
                setTaskCardFields({ finish: { value: 99 } });
            } else {
                setTaskCardFields({ finish: { value: value } });
            }
        } else {
            if (value > 100) {
                setTaskCardFields({ finish: { value: 100 } });
            } else {
                setTaskCardFields({ finish: { value: value } });
            }
        }
    }


    setNewTaskValue = (fieldname, v) => {
        if (fieldname == "startenddate") {
            this.setState({
                taskInfo: {
                    ...this.state.taskInfo,
                    begindate: v[0],
                    enddate: v[1]
                },
            });
        } else if (fieldname == "subject") {
            this.setState({
                taskInfo: {
                    ...this.state.taskInfo,
                    subject:  v
                },
            });
        } else if (fieldname == "hrmid") {
            this.setState({
                taskInfo: {
                    ...this.state.taskInfo,
                    hrmid: v.hrmid,
                    hrmname: v.hrmname,
                },
            });
        }
    }

    saveTask = (e) => { 
        e.stopPropagation();
        const { boardStore } = this.props;
        boardStore.saveTaskInfo();
    }

    saveSubTask = () => {
        const { hrmid, begindate, enddate, subject } = this.state.taskInfo;
        if (hrmid == "") {
            Modal.warning({
                title: "系统提示",
                content: "请选择任务负责人！"
            });
        } else if (begindate == "") {
            Modal.warning({
                title: "系统提示",
                content: "请选择任务开始结束时间！"
            });
        } else if (subject == "") {
            Modal.warning({
                title: "系统提示",
                content: "请填写任务名称！"
            });
        } else {
            this.props.contentStore.saveSubTaskInfo({
                subject: subject,
                hrmid: hrmid,
                begindate: begindate,
                enddate: enddate,
                parentid : this.props.contentStore.taskid,
                prjid : this.props.prjid
            });

            $("#addTaskLine").css("display", "none");
            $("#addTaskBtn").css("display", "");
            jQuery("#addSubTaskInput").val("");
            this.setState({
                taskInfo:{
                subject: "",
                hrmid: "",
                hrmname: "",
                begindate: "",
                enddate: ""
            }
            });
        }
    }
}